<template>
  <el-dialog title="发起会议" :visible="createMeetingVisible" width="60%" :center="true" :close-on-click-modal="false"
             @close="closeDialog">
    <el-form :model="meetingDTO" size="small" label-width="80px" label-position="left" style="padding: 0 40px">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="会议名称">
            <el-input v-model="meetingDTO.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发起部门">
            <el-input v-model="meetingDTO.organizerDeprt"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="会议主题">
            <el-input v-model="meetingDTO.subject" style="width: 100%" type="textarea" rows="5"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="起止时间">
            <el-date-picker style="width: 100% " format="yyyy-MM-dd HH:mm"
                            v-model="meetingDTO.meetingTime"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地点">
            <el-input v-model="meetingDTO.address" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="主持人">
            <el-cascader style="width: 100%"
                         :options="optionsHeader" v-model="meetingDTO.host">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="参会人" style="padding-left: 40px">
            <el-cascader style="width: 100%"
                         :options="optionsHeader"
                         :props="props" v-model="meetingDTO.meetingAttendeesList">
            </el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
        <el-form-item label="会议议程" style="width: 100%">
          <el-table :data="meetingDTO.meetingAgendaList" border style="width: 100%">
            <el-table-column type="index" width="50px" label="序号"></el-table-column>
            <el-table-column label="内容">
              <template slot-scope="scope">
                <el-input v-model="scope.row.agenda" placeholder="请输入事项名称"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="主持人" width="100px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.host"></el-input>
              </template>
            </el-table-column>
            <el-table-column min-width="10%">
              <template slot-scope="scope">
                <el-button @click="addMeetingItem(scope.$index)" type="text" size="small">
                  <i class="el-icon-plus"></i>
                </el-button>
                <el-button @click="deleteMeetingItem(scope.$index)" type="text" size="small"
                           v-if="meetingDTO.meetingAgendaList.length > 1">
                  <i class="el-icon-minus"></i>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="会议要求">
            <el-input v-model="meetingDTO.requirement" style="width: 100%" type="textarea" rows="5"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
                class="upload-demo"
                :action="uploadAction"
                multiple
                :on-success="handleSuccess"
                :file-list="meetingFileList" :with-credentials="true">
              <el-button><i class="el-icon-paperclip"></i></el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="generatePDF" size="mini" type="text">生成会议通知</el-button>
      <el-button type="primary" @click="release" size="mini">发 起</el-button>
      <el-button type="primary" @click="cancle" size="mini">取 消</el-button>
    </div>
    <div id="pdf-content" ref="pdfContent" style="display: none;">
      <h1 style="font-family: '宋体', SimSun; font-size: 22px; font-weight: bold; text-align: center;
  margin-bottom: 20px;">{{ meetingDTO.name }}</h1>
      <p style=" line-height: 28px; margin-bottom: 0; font-weight: 100; text-align: center">{{
          meetingDTO.organizerDeprt
        }}</p>
      <p class="pdfP">{{ meetingDTO.subject }}</p>
      <p class="pdfP">一、会议时间及地点</p>
      <p class="pdfP">
        会议时间：{{ formatDateTimeRange(meetingDTO.meetingTime) }}</p>
      <p class="pdfP">会议地点：{{ meetingDTO.address }}</p>
      <p class="pdfP">二、主持人：{{ getFullName(meetingDTO.host) }}</p>
      <p class="pdfP">
        三、参会人：{{ meetingDTO.meetingAttendeesList.map(item => getFullName(item)).join('、') }}</p>
      <p class="pdfP">四、会议议程：</p>
      <table
          style="width:100%; text-indent: 2em; margin: 14px auto; border-top: 1px solid #000; border-bottom: 1px solid #545454; border-collapse: collapse;">
        <thead>
        <tr>
          <th class="pdfTh">
            序号
          </th>
          <th class="pdfTh">
            内容
          </th>
          <th class="pdfTh">
            主持人
          </th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in meetingDTO.meetingAgendaList" :key="index">
          <td class="pdfTd">{{ index + 1 }}</td>
          <td class="pdfTd">{{ item.agenda }}</td>
          <td class="pdfTd">{{ item.host }}</td>
        </tr>
        </tbody>
      </table>
      <p class="pdfP">五、会议要求：{{ meetingDTO.requirement }}</p>
      <p class="pdfP">
        六、附件：{{ meetingFileList.map(file => file.name).join(', ') }}</p>
      <p style=" line-height: 28px; margin-top: 30px; text-indent: 2em; margin-bottom: 0; text-align: right">
        {{ meetingDTO.organizerDeprt }}</p>
      <p style=" line-height: 28px;  text-indent: 2em; margin-bottom: 0; text-align: right">{{
          formatCurrentDate()
        }}</p>
    </div>
  </el-dialog>
</template>

<script>
import html2pdf from 'html2pdf.js';
import {optionsHeader} from "@/utils/optionsHeader";

export default {
  name: "CreateMeeting",
  props: {
    createMeetingVisible: Boolean,
    meetingDTO: Object,
  },
  data() {
    return {
      uploadAction: `${process.env.VUE_APP_API_BASE_URL}/file/upload`,
      meetingFileList: [],
      props: {multiple: true},
      optionsHeader: optionsHeader
    }
  },
  methods: {
    closeDialog() {
      this.$emit('update:createMeetingVisible', false)
    },
    addMeetingItem() {
      this.meetingDTO.meetingAgendaList.push({agenda: '', host: ''})
    },
    deleteMeetingItem(index) {
      if (this.meetingDTO.meetingAgendaList.length != 1)
        this.meetingDTO.meetingAgendaList.splice(index, 1)
      else alert("至少需要保留一条会议议程")
    },
    release() {
      this.$emit('release', {meetingDTO: this.meetingDTO})
      this.$emit('update:createMeetingVisible', false)
    },
    cancle() {
      this.$emit('update:createMeetingVisible', false)
    },
    handleSuccess(response, file, fileList) {
      console.log(response.data);
      const attachment = {
        filePath: response.data,
        source: '会议发布时'
      };
      this.meetingDTO.attachment.push(attachment);
    },
    generatePDF() {
      const element = this.$refs.pdfContent;
      if (!element) {
        console.error('pdf-content 元素未找到');
        return;
      }
      console.log('正在生成 PDF，内容预览:', element.innerHTML); // 调试内容
      element.style.display = 'block';
      const filename = encodeURI(`${this.meetingDTO.name || '未命名会议'}通知.pdf`); // 确保文件名有效
      console.log('生成的文件名:', filename); // 调试文件名

      // 配置 html2pdf 选项
      const options = {
        margin: 10,
        filename: filename,
        image: {type: 'jpeg', quality: 0.98},
        html2canvas: {
          scale: 3,
          useCORS: true,
          logging: true,
          letterRendering: true,
          backgroundColor: null,
          allowTaint: false, // 不允许跨域污染
          taintTest: false, // 不进行跨域污染测试
          dpi: window.devicePixelRatio * 300 // 设置 DPI 以提高清晰度
        },
        jsPDF: {unit: 'mm', format: 'a4', orientation: 'portrait'}
      };

      // 使用 html2pdf 库生成 PDF
      html2pdf()
          .from(element)
          .set(options)
          .toPdf()
          .get('pdf')
          .then((pdf) => {
            try {
              pdf.save(filename);
              element.style.display = 'none';
            } catch (error) {
              console.error('处理 PDF 时出错:', error);
              this.$message.error('生成 PDF 失败，请重试');
              element.style.display = 'none';
            }
          })
          .catch((error) => {
            console.error('生成 PDF 时出错:', error);
            this.$message.error('生成 PDF 失败，可能存在网络或内容问题');
            element.style.display = 'none';
          });
    },
    getFullName(path) {
      if (!path || path.length === 0) return '';
      const lastValue = path[path.length - 1];
      for (const department of this.optionsHeader) {
        for (const person of department.children) {
          if (person.value === lastValue) {
            return person.label;
          }
        }
      }
      return '';
    },
    formatDateTimeRange(range) {
      if (!range || range.length !== 2) return '';
      const format = (date) => date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
      return `${format(range[0])} 至 ${format(range[1])}`;
    },
    formatCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year} 年 ${month} 月 ${day} 日`;
    }

  },
}
</script>

<style scoped>
::v-deep #pdf-content {
  display: none;
  font-family: '仿宋', SimSun;
  background-color: transparent; /* 确保背景透明 */
}

::v-deep .pdfP {
  font-weight: 100 !important;
  text-shadow: none !important;
  line-height: 28px;
  text-indent: 2em;
  margin-bottom: 0;
  -webkit-font-smoothing: antialiased; /* 抗锯齿 */
  -moz-osx-font-smoothing: grayscale; /* 抗锯齿 */
}

::v-deep .pdfTh {
  border-bottom: 1px solid #000;
  text-align: center;
  line-height: 20px;
  font-weight: 100;
  padding: 10px 0;
  font-size: 15px;
}

::v-deep .pdfTd {
  text-align: left;
  line-height: 20px;
  padding: 10px 0;
  font-size: 15px;
  font-weight: 100;
}

::v-deep #pdf-content .department {
  text-align: right;
  font-family: '楷体', KaiTi;
  font-weight: 100;
  margin-bottom: 10px;
}

::v-deep #pdf-content .date {
  text-align: right;
  font-weight: 100;
  margin-top: 10px;
}
</style>